package com.moody.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.moody.hibernate.domain.CustInfo;
import com.moody.hibernate.domain.DebtInfo;
import com.moody.hibernate.domain.IndInfo;
import com.moody.hibernate.domain.ModelInfo;
import com.moody.hibernate.domain.OrgInfo;
import com.moody.hibernate.domain.PdH;
import com.moody.hibernate.domain.ReportList;
import com.moody.hibernate.domain.RightInfo;
import com.moody.hibernate.domain.RoleInfo;
import com.moody.hibernate.domain.RoleRight;
import com.moody.hibernate.domain.RoleRightId;
import com.moody.hibernate.domain.UserInfo;
import com.moody.hibernate.domain.UserRole;
import com.moody.hibernate.domain.UserRoleId;
import com.moody.service.CustomerService;
import com.moody.service.ObligationService;
import com.moody.service.RatingService;
import com.moody.service.SystemService;
import com.moody.util.CalendarUtil;

/*
 * Copyright © Moody analytics
 *
 * @Author: Wang Fuqiang
 * @Time: 2011-12-30 下午13:43:35
 * @Modified by: Fuqiang Wang
 * @Description: 
 */

@Controller
@RequestMapping("/system")
public class SystemController {
	private static final Logger log = LoggerFactory
			.getLogger(SystemController.class);
	WebApplicationContext web = ContextLoader.getCurrentWebApplicationContext();
	ServletContext context = web.getServletContext();  
	WebApplicationContext ctx  = WebApplicationContextUtils.getWebApplicationContext(context);

	@Resource
	private SystemService systemService;
	@Resource
	private CustomerService customerService;
	@Resource
	private ObligationService obligationService;
	@Resource
	private RatingService ratingService;

	@RequestMapping("/listOrg")
	public void listOrg(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		List<OrgInfo> orgList = new ArrayList<OrgInfo>();

		// 寻找这个节点下所有的机构
		if (request.getSession().getAttribute("orgId") != null
				&& !request.getSession().getAttribute("orgId").toString()
						.equals("0")) {
			String orgId = request.getSession().getAttribute("orgId")
					.toString();
			List<OrgInfo> list = systemService.findAllOrg();
			for (OrgInfo org : list) {
				if (org.getOrgCode().equals(
						systemService.findOrgById(orgId).getOrgId())) {
					orgList.add(org);
				}
			}

			String flag = request.getSession().getAttribute("leafFlag")
					.toString();

			if (flag.equals("true")) {
				orgList = new ArrayList<OrgInfo>();
				orgList.add(systemService.findOrgById(orgId));
			}

		} else {
			orgList = systemService.findAllOrg();
		}

		Integer totalSize = orgList.size();

		// 分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));

		// 分页
		List<OrgInfo> pageList;
		if (orgList.size() > start + limit)
			pageList = orgList.subList(start, limit + start);
		else
			pageList = orgList.subList(start, orgList.size());

		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", totalSize);
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO = JSONObject.fromObject(myCustMap);
		out.print(myCustJO);

//		log.info("JSON数据：" + myCustJO);
	}

	@RequestMapping("/deleteOrg")
	public void deleteOrg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String orgId = request.getParameter("orgId");
		OrgInfo org = systemService.findOrgById(orgId);

		if (org != null) {
			systemService.deleteOrgInfoById(orgId);
			response.getWriter().print("{success:true}");
		} else {
			response.getWriter().print("{success:false}");
		}
	}

	@RequestMapping("/showOrgTree")
	public void showOrgTree(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		List<Map> resultList = new ArrayList<Map>();
		List<OrgInfo> orgList = systemService.findAllOrg();

		for (OrgInfo org : orgList) {
			// 第一层
			if (org.getOrgCode().equals("0")) {
				Map levelOneMap = new HashMap();
				levelOneMap.put("id", org.getOrgId());
				levelOneMap.put("text", org.getOrgname());

				Boolean flag = false;
				// 有children置为非叶节点否则置为叶子
				for (OrgInfo org1 : orgList) {
					if (org.getOrgId().equals(org1.getOrgCode())) {
						flag = true;
					}
				}
				if (flag)
					levelOneMap.put("children", new ArrayList());
				else
					levelOneMap.put("leaf", true);
				resultList.add(levelOneMap);
			}
		}

		for (OrgInfo org : orgList) {
			// 处理第二层
			if (!org.getOrgCode().equals("0")) {
				String levelOneId = org.getOrgCode();

				for (Map levelOneOrg : resultList) {
					if (levelOneOrg.get("id").equals(org.getOrgCode())) {
						Map<String, Object> levelTwoMap = new HashMap<String, Object>();
						levelTwoMap.put("id", org.getOrgId());
						levelTwoMap.put("text", org.getOrgname());
						levelTwoMap.put("leaf", true);
						((ArrayList) levelOneOrg.get("children"))
								.add(levelTwoMap);
					}
				}
			}
		}

		JSONArray JA = JSONArray.fromObject(resultList);

		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		response.getWriter().print(JA);

	}

	@RequestMapping("/addOrg")
	public void addOrg(HttpServletRequest request,
			HttpServletResponse response, OrgInfo org) throws IOException {
		String orgCodeValue = request.getParameter("orgCodeValue");

		org.setOrgCode(orgCodeValue);
		org.setInputDate(CalendarUtil.getCurrentDateStr());
		org.setUpdateDate(CalendarUtil.getCurrentDateStr());
		systemService.insertOrg(org);

		response.getWriter().print("{success:true}");
	}

	@RequestMapping("/getOrg")
	public void getOrg(HttpServletRequest request,
			HttpServletResponse response, OrgInfo org) throws IOException {
		String orgId = request.getParameter("orgId");
		OrgInfo orgInfo = new OrgInfo();
		orgInfo = systemService.findOrgById(orgId);
		if (orgInfo.getOrgCode().equals("0"))
			orgInfo.setOrgCode("清远农商行总行");
		else
			orgInfo.setOrgCode(systemService.findOrgById(orgInfo.getOrgCode())
					.getOrgname());
		org.setUpdateDate(CalendarUtil.getCurrentDateStr());
		JSONObject debtJO = JSONObject.fromObject(orgInfo);
		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(debtJO);

//		log.info("JSON数据：" + debtJO);
	}

	@RequestMapping("/editOrg")
	public void editOrg(HttpServletRequest request,
			HttpServletResponse response, OrgInfo org) throws IOException {
		String orgId = request.getParameter("orgId");
		org.setOrgId(orgId);
		org.setUpdateDate(CalendarUtil.getCurrentDateStr());
		String orgCodeValue = request.getParameter("orgCodeValue");
		if (orgCodeValue != null && !orgCodeValue.equals(""))
			org.setOrgCode(orgCodeValue);
		else
			org.setOrgCode(systemService.findOrgById(orgId).getOrgCode());
		systemService.updateOrg(org);

		response.getWriter().print("{success:true}");
	}

	// 加载某节点下的机构
	@RequestMapping("/loadTreeFromParent")
	public void loadTreeFromParent(HttpServletRequest request,
			HttpServletResponse response, OrgInfo org) throws IOException {
		String orgId = request.getParameter("orgId");
		request.getSession().removeAttribute("orgId");
		request.getSession().setAttribute("orgId", orgId);
		request.getSession().removeAttribute("leafFlag");
		request.getSession().setAttribute("leafFlag",
				request.getParameter("isLeaf"));

		response.getWriter().print("{success:true}");
	}

	@RequestMapping("/findUser")
	public void findUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String conditionKey = request.getParameter("condition");
		String conditionValue = request.getParameter("keyword");
		
		Map<String,String> condition = new LinkedHashMap<String,String>();
		condition.put(conditionKey, conditionValue);
		List<UserInfo> userList = systemService.findUserByCondition(condition);
		
		for(UserInfo user:userList){
			user.setBelongorgName(systemService.findOrgById(user.getBelongorg()).getOrgname());
		}

		Integer totalSize = userList.size();

		// 分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));

		// 分页
		List<UserInfo> pageList;
		if (userList.size() > start + limit)
			pageList = userList.subList(start, limit + start);
		else
			pageList = userList.subList(start, userList.size());

		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", totalSize);
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO = JSONObject.fromObject(myCustMap);
		out.print(myCustJO);

//		log.info("JSON数据：" + myCustJO);
	}
	
		
	@RequestMapping("/listUser")
	public void listUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		List<UserInfo> userList = new ArrayList<UserInfo>();

		// 寻找这个节点下所有的机构
		if (request.getSession().getAttribute("userOrgId") != null) {
			String orgId = request.getSession().getAttribute("userOrgId")
					.toString();
			List<UserInfo> list = systemService.findAllUser();
			for (UserInfo user : list) {
				if (user.getBelongorg().equals(orgId)) {
					userList.add(user);
				}
			}
		} else {
			userList = systemService.findAllUser();
		}
		for(UserInfo user:userList){
			user.setBelongorgName(systemService.findOrgById(user.getBelongorg()).getOrgname());
		}

		Integer totalSize = userList.size();

		// 分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));

		// 分页
		List<UserInfo> pageList;
		if (userList.size() > start + limit)
			pageList = userList.subList(start, limit + start);
		else
			pageList = userList.subList(start, userList.size());

		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", totalSize);
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO = JSONObject.fromObject(myCustMap);
		out.print(myCustJO);

//		log.info("JSON数据：" + myCustJO);
	}

	@RequestMapping("/deleteUser")
	public void deleteUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String userId = request.getParameter("userId");
		UserInfo user = systemService.findUserById(userId);

		if (user != null) {
			systemService.deleteUserInfoById(userId);
			response.getWriter().print("{success:true}");
		} else {
			response.getWriter().print("{success:false}");
		}
	}

	@RequestMapping("/addUser")
	public void addUser(HttpServletRequest request,
			HttpServletResponse response, UserInfo user) throws IOException {
		String orgCodeValue = request.getParameter("orgCodeValue");

		user.setBelongorg(orgCodeValue);
		user.setInputDate(CalendarUtil.getCurrentDateStr());
		user.setUpdateDate(CalendarUtil.getCurrentDateStr());
		systemService.insertUser(user);

		response.getWriter().print("{success:true}");
	}

	@RequestMapping("/getUser")
	public void getUser(HttpServletRequest request,
			HttpServletResponse response, UserInfo user) throws IOException {
		String userId = request.getParameter("userId");
		UserInfo userInfo = new UserInfo();
		userInfo = systemService.findUserById(userId);
		if (userInfo.getBelongorg().equals("0"))
			userInfo.setBelongorg("清远农商行总行");
		else
			userInfo.setBelongorg(systemService.findOrgById(
					userInfo.getBelongorg()).getOrgname());
		userInfo.setUpdateDate(CalendarUtil.getCurrentDateStr());
		JSONObject debtJO = JSONObject.fromObject(userInfo);
		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(debtJO);

//		log.info("JSON数据：" + debtJO);
	}

	@RequestMapping("/editUser")
	public void editUser(HttpServletRequest request,
			HttpServletResponse response, UserInfo user) throws IOException {
		String userId = request.getParameter("userId");
		user.setUserId(userId);
		user.setUpdateDate(CalendarUtil.getCurrentDateStr());
		String orgCodeValue = request.getParameter("orgCodeValue");
		if (orgCodeValue != null && !orgCodeValue.equals(""))
			user.setBelongorg(orgCodeValue);
		else
			user.setBelongorg(systemService.findUserById(userId).getBelongorg());
		systemService.updateUser(user);

		response.getWriter().print("{success:true}");
	}
	
	@RequestMapping("/transferCustomer")
	public void transferCustomer(HttpServletRequest request,
			HttpServletResponse response, UserInfo user) throws IOException {
		boolean isRetail = false;
		String custId = request.getParameter("custId");
		String transferUser = request.getParameter("transferUser");
		String transferOrg = systemService.findUserById(transferUser).getBelongorg();

		//转移客户
		CustInfo custInfo = customerService.findCustByCustId(custId);
		if(custInfo != null){
			custInfo.setInputUserId(transferUser);
			custInfo.setInputOrgId(transferOrg);	
			customerService.updateCustInfo(custInfo);
		}
		else{
			IndInfo indInfo = customerService.findIndCustByCustId(custId);
			if(indInfo == null) {
				response.getWriter().print("{success:false}");
				return;
			}
			indInfo.setInputUserId(transferUser);
			indInfo.setInputOrgId(transferOrg);
			customerService.updateIndCustInfo(indInfo);
		}

		
		
		//转移评级
		List<PdH> pdList = ratingService.findHistoryRatingPdH(custId);
		for(PdH pdh : pdList){
			pdh.setFirstUserId(transferUser);
			pdh.setFirstOrgId(transferOrg);
		}
		
		response.getWriter().print("{success:true}");
	}


	@RequestMapping("/transferUser")
	public void transferUser(HttpServletRequest request,
			HttpServletResponse response, UserInfo user) throws IOException {
		String userId = request.getParameter("userId");
		String orgId = systemService.findUserById(userId).getBelongorg();
		String transferUser = request.getParameter("transferUser");
		String transferOrg = systemService.findUserById(userId).getBelongorg();

		//判断userId是客户经理
		Boolean flag = false;
		List<RoleInfo> roleList = systemService.findRoleByUserId(userId);
		for(RoleInfo roleInfo : roleList){
			if(roleInfo.getRoleName().contains("客户经理")){
				flag = true;
			}
		}

		if(flag){
			//首先把客户移交至transferUser
			//对公客户
			Map<String,String> custInfoCondition = new LinkedHashMap<String,String>();
			systemService.findOrgById(systemService.findUserById(userId).getBelongorg());
			custInfoCondition.put("inputUserId", userId);
			List<CustInfo> custInfoList = customerService.findCustByCondition(custInfoCondition, userId, orgId);
			for(CustInfo custInfo : custInfoList){
				custInfo.setInputUserId(transferUser);
				custInfo.setInputOrgId(transferOrg);	
				customerService.updateCustInfo(custInfo);
				
				//转移财报
//				List<ReportList> reportList = customerService.findReportListByCustId(custInfo.getCustId());
//				for(ReportList report : reportList){
//					report.getId().setCustId(transferUser);
//					customerService.updateReportList(report);
//				}
				
				//转移债项
				List<DebtInfo> debtList = obligationService.findDebtByCustId(custInfo.getCustId());
				for(DebtInfo debt : debtList){
					debt.setInputUserId(transferUser);
					debt.setInputOrgId(transferOrg);
					obligationService.updateDebtInfo(debt);
				}
				
				//转移评级
				List<PdH> pdList = ratingService.findHistoryRatingPdH(custInfo.getCustId());
				for(PdH pdh : pdList){
					pdh.setFirstUserId(transferUser);
					pdh.setFirstOrgId(transferOrg);
				}
			}
			
			//零售客户
			List<IndInfo> indInfoList = customerService.findIndCustByCondition(custInfoCondition, userId, orgId);
			for(IndInfo indInfo : indInfoList){
				indInfo.setInputUserId(transferUser);
				indInfo.setInputOrgId(transferOrg);	
				customerService.updateIndCustInfo(indInfo);
			}
					
			response.getWriter().print("{success:true}");
		}else{
			response.getWriter().print("{success:false}");
		}
		

		
	}
	
	@RequestMapping("/initUserPassword")
	public void initUserPassword(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String userId = request.getParameter("userId");
		UserInfo user = systemService.findUserById(userId);

		if (user != null) {
			user.setPassword("0000000000");
			systemService.updateUser(user);
			response.getWriter().print("{success:true}");
		} else {
			response.getWriter().print("{success:false}");
		}
	}
	
	
	@RequestMapping("/modifyPassword")
	public String modifyPassword(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String password1 = request.getParameter("password1");
		UserInfo user = (UserInfo) request.getSession().getAttribute("logonUser");
		String orginPassword = user.getPassword();
		user.setPassword(password1);
		systemService.updateUser(user);
		
		request.getSession().removeAttribute("password");
		request.getSession().setAttribute("password", user.getPassword());
		
		response.setContentType("text/html;charset=UTF-8");  
        response.setCharacterEncoding("utf-8");  
        response.getWriter().write("<script language=javascript>alert('密码修改成功！');</script>");
        
        request.setAttribute("error", 1);
        request.setAttribute("orginPassword", orginPassword);
        request.setAttribute("password1", password1);
        request.setAttribute("password2", password1);
        
        return "ModifyPassword";
	}
	
	

	@RequestMapping("/loadUserTreeFromParent")
	public void loadUserTreeFromParent(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String orgId = request.getParameter("orgId");
		request.getSession().removeAttribute("userOrgId");
		request.getSession().setAttribute("userOrgId", orgId);

		response.getWriter().print("{success:true}");
	}

	@RequestMapping("/listRole")
	public void listRole(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		List<RoleInfo> roleList = new ArrayList<RoleInfo>();

		roleList = systemService.findAllRole();

		Integer totalSize = roleList.size();

		// 分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));

		// 分页
		List<RoleInfo> pageList;
		if (roleList.size() > start + limit)
			pageList = roleList.subList(start, limit + start);
		else
			pageList = roleList.subList(start, roleList.size());

		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", totalSize);
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO = JSONObject.fromObject(myCustMap);
		out.print(myCustJO);

//		log.info("JSON数据：" + myCustJO);
	}

	@RequestMapping("/addRole")
	public void addRole(HttpServletRequest request,
			HttpServletResponse response, RoleInfo role) throws IOException {

		role.setInputDate(CalendarUtil.getCurrentDateStr());
		role.setUpdateDate(CalendarUtil.getCurrentDateStr());
		systemService.insertRole(role);

		response.getWriter().print("{success:true}");
	}

	@RequestMapping("/getRole")
	public void getRole(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String roleId = request.getParameter("roleId");
		RoleInfo role = new RoleInfo();
		role = systemService.findRoleById(roleId);

		JSONObject debtJO = JSONObject.fromObject(role);
		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(debtJO);

//		log.info("JSON数据：" + debtJO);
	}

	@RequestMapping("/editRole")
	public void editRole(HttpServletRequest request,
			HttpServletResponse response, RoleInfo role) throws IOException {
		String roleId = request.getParameter("roleId");
		role.setRoleId(request.getParameter("roleId"));
		role.setUpdateDate(CalendarUtil.getCurrentDateStr());
		role.setInputDate(systemService.findRoleById(roleId).getInputDate());
		systemService.updateRole(role);
		response.getWriter().print("{success:true}");
	}

	@RequestMapping("/deleteRole")
	public void deleteRole(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String roleId = request.getParameter("roleId");
		RoleInfo role = systemService.findRoleById(roleId);

		if (role != null) {
			systemService.deleteRoleInfoById(roleId);
			response.getWriter().print("{success:true}");
		} else {
			response.getWriter().print("{success:false}");
		}
	}

	@RequestMapping("/listRight")
	public void listRight(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		List<RightInfo> roleList = new ArrayList<RightInfo>();

		roleList = systemService.findAllRight();

		Integer totalSize = roleList.size();

		// 分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));

		// 分页
		List<RightInfo> pageList;
		if (roleList.size() > start + limit)
			pageList = roleList.subList(start, limit + start);
		else
			pageList = roleList.subList(start, roleList.size());

		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", totalSize);
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO = JSONObject.fromObject(myCustMap);
		out.print(myCustJO);

//		log.info("JSON数据：" + myCustJO);
	}

	@RequestMapping("/addRight")
	public void addRight(HttpServletRequest request,
			HttpServletResponse response, RightInfo right) throws IOException {

		right.setInputDate(CalendarUtil.getCurrentDateStr());
		right.setUpdateDate(CalendarUtil.getCurrentDateStr());
		systemService.insertRight(right);

		response.getWriter().print("{success:true}");
	}

	@RequestMapping("/getRight")
	public void getRight(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String roleId = request.getParameter("rightId");
		RightInfo right = new RightInfo();
		right = systemService.findRightById(roleId);

		JSONObject debtJO = JSONObject.fromObject(right);
		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(debtJO);

		//log.info("JSON数据：" + debtJO);
	}

	@RequestMapping("/editRight")
	public void editRight(HttpServletRequest request,
			HttpServletResponse response, RightInfo right) throws IOException {
		String rightId = request.getParameter("rightId");
		right.setRightId(request.getParameter("rightId"));
		right.setUpdateDate(CalendarUtil.getCurrentDateStr());
		right.setInputDate(systemService.findRightById(rightId).getInputDate());
		systemService.updateRight(right);
		response.getWriter().print("{success:true}");
	}

	@RequestMapping("/deleteRight")
	public void deleteRight(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String rightId = request.getParameter("rightId");
		RightInfo right = systemService.findRightById(rightId);

		if (right != null) {
			systemService.deleteRightInfoById(rightId);
			response.getWriter().print("{success:true}");
		} else {
			response.getWriter().print("{success:false}");
		}
	}

	// 用户关联角色
	@RequestMapping("/associateRole")
	public String associateRole(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String userId = request.getParameter("userId");
		UserInfo user = systemService.findUserById(userId);
		request.getSession().removeAttribute("associateUser");
		request.getSession().setAttribute("associateUser", user);

		return "system/UserRole";
	}

	// 查看用户关联角色
	@RequestMapping("/viewUserRole")
	public void viewUserRole(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		UserInfo user = (UserInfo) request.getSession().getAttribute(
				"associateUser");

		List<RoleInfo> roleList = systemService.findRoleByUserId(user
				.getUserId());
		List<RoleInfo> allRoleList = systemService.findAllRole();

		// 已选的设置checkSelect为true
		for (RoleInfo role : allRoleList) {
			Boolean flag = false;
			role.setCheckSelect(flag);
			for (RoleInfo selectRole : roleList) {
				if (role.getRoleId().equals(selectRole.getRoleId())) {
					flag = true;
				}
				if (flag) {
					role.setCheckSelect(flag);
					break;
				}
			}
		}

		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", allRoleList.size());
		myCustMap.put("resultData", allRoleList);
		JSONObject myCustJO = JSONObject.fromObject(myCustMap);
		out.print(myCustJO);

		//log.info("JSON数据：" + myCustJO);

	}

	// 修改用户关联角色
	@RequestMapping("/modifyUserRole")
	public void modifyUserRole(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		UserInfo user = (UserInfo) request.getSession().getAttribute(
				"associateUser");
		String data = request.getParameter("newRecord");
		JSONArray jsonArray = JSONArray.fromObject(data);
		//log.info("data: " + data);
		// 先将data遍历去重
		Map<String, RoleInfo> roleMap = new HashMap<String, RoleInfo>();
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			RoleInfo role = (RoleInfo) JSONObject.toBean(jsonObject,
					RoleInfo.class);
			roleMap.put(role.getRoleId(), role);
		}

		JSONObject myCustJO = JSONObject.fromObject(roleMap);
		//log.info("data2: " + myCustJO);

		List<UserRole> orginList = systemService.findUserRoleByUserId(user
				.getUserId());

		List<UserRole> userRoleList = new ArrayList<UserRole>();
		// 先清空
		systemService.deleteUserRoleByUserId(user.getUserId());
		// 之前存在并且未修改过的，先加入

		for (UserRole orginUserRole : orginList) {
			// 之前存在
			Boolean flag = true;
			for (String key : roleMap.keySet()) {
				RoleInfo role = roleMap.get(key);
				if (orginUserRole.getId().getRoleId().equals(role.getRoleId())) {
					flag = false;
				}
			}
			if (flag) {
				userRoleList.add(orginUserRole);
			}
		}

		// 再将选中的加入
		for (String key : roleMap.keySet()) {
			RoleInfo role = roleMap.get(key);

			if (role.getCheckSelect()) {
				UserRole userRole = new UserRole();
				UserRoleId id = new UserRoleId();
				id.setUserId(user.getUserId());
				id.setRoleId(role.getRoleId());
				userRole.setId(id);
				userRoleList.add(userRole);
			}
		}
		// 批量插入
		systemService.insertUserRole(userRoleList);

		response.getWriter().print("{success:true}");
	}

	// 角色关联权限
	@RequestMapping("/associateRight")
	public String associateRight(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String roleId = request.getParameter("roleId");
		RoleInfo role = systemService.findRoleById(roleId);
		request.getSession().removeAttribute("associateRole");
		request.getSession().setAttribute("associateRole", role);

		return "system/RoleRight";
	}

	// 查看角色关联权限
	@RequestMapping("/viewRoleRight")
	public void viewRoleRight(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		RoleInfo role = (RoleInfo) request.getSession().getAttribute(
				"associateRole");

		List<RightInfo> rightList = systemService.findRightByRoleId(role
				.getRoleId());
		List<RightInfo> allRightList = systemService.findAllRight();

		// 已选的设置checkSelect为true
		for (RightInfo right : allRightList) {
			Boolean flag = false;
			right.setCheckSelect(flag);
			for (RightInfo selectRight : rightList) {
				if (right.getRightId().equals(selectRight.getRightId())) {
					flag = true;
				}
				if (flag) {
					right.setCheckSelect(flag);
					break;
				}
			}
		}

		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", allRightList.size());
		myCustMap.put("resultData", allRightList);
		JSONObject myCustJO = JSONObject.fromObject(myCustMap);
		out.print(myCustJO);

		//log.info("JSON数据：" + myCustJO);

	}

	// 修改角色关联权限
	@RequestMapping("/modifyRoleRight")
	public void modifyRoleRight(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		RoleInfo role = (RoleInfo) request.getSession().getAttribute(
				"associateRole");
		String data = request.getParameter("newRecord");

		JSONArray jsonArray = JSONArray.fromObject(data);
		//log.info("data: " + data);
		// 先将data遍历去重
		Map<String, RightInfo> rightMap = new HashMap<String, RightInfo>();
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			RightInfo right = (RightInfo) JSONObject.toBean(jsonObject,
					RightInfo.class);
			rightMap.put(right.getRightId(), right);
		}

		JSONObject myCustJO = JSONObject.fromObject(rightMap);
		//log.info("data2: " + myCustJO);

		List<RoleRight> orginList = systemService.findRoleRightByRoleId(role
				.getRoleId());

		List<RoleRight> roleRightList = new ArrayList<RoleRight>();
		// 先清空
		systemService.deleteRoleRightByUserId(role.getRoleId());
		// 之前存在并且未修改过的，先加入

		for (RoleRight orginRoleRight : orginList) {
			// 之前存在
			Boolean flag = true;
			for (String key : rightMap.keySet()) {
				RightInfo right = rightMap.get(key);
				if (orginRoleRight.getId().getRightId().equals(right.getRightId())) {
					flag = false;
				}
			}
			if (flag) {
				roleRightList.add(orginRoleRight);
			}
		}

		// 再将选中的加入
		for (String key : rightMap.keySet()) {
			RightInfo right = rightMap.get(key);

			if (right.getCheckSelect()) {
				RoleRight roleRight = new RoleRight();
				RoleRightId id = new RoleRightId();
				id.setRoleId(role.getRoleId());
				id.setRightId(right.getRightId());
				roleRight.setId(id);
				roleRightList.add(roleRight);
			}
		}
		// 批量插入
		systemService.insertRoleRight(roleRightList);

		response.getWriter().print("{success:true}");
	}
}
